package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.Category;
import com.example.domain.Dish;
import com.example.domain.DishFlavor;
import com.example.domain.Employee;
import com.example.dto.DishDto;
import com.example.service.CategoryService;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页、查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> getDishPage(@PathParam("page") Integer page, @PathParam("pageSize") Integer pageSize, @PathParam("name") String name) {
        //查询数据库数据
        Page<Dish> pageInfo = dishService.getDishListForPage(page, pageSize, name);
        //映射
        Page<DishDto> dishDtoPage = dishService.dishToDishDto(pageInfo);

        return R.success(dishDtoPage);
    }

    /**
     * 删除单个或者多个
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> deleteDish(Long[] ids) {
        try {
            boolean b = dishService.deleteByIds(ids);
            if (b) {
                //清理所有缓存
                Set keys = redisTemplate.keys("dish_*");
                redisTemplate.delete(keys);
                return R.success("删除成功");
            }
            return R.error("删除失败");
        } catch (Exception exception) {
            exception.printStackTrace();
            return R.error("删除失败");
        }
    }

    /**
     * 更改菜品是否起售状态
     *
     * @param status
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> dishStatusByStatus(@PathVariable Integer status, @PathParam("ids") Long[] ids, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            dishService.dishStatusByStatus(status, ids, session);
            //清理所有缓存
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("更改成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return R.error("更改失败");
        }
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @Transactional
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //清理所有缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("新增菜品成功");
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> queryDishById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //清理所有缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("新增菜品成功");
    }

    /**
     * 获得数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        //构建Key，用于存数据在Redis中，也就是用来表示条件和区分用的
        //动态构造Key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从Redis中获取无缓存数据
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在，直接返回，无需查询数据库
        if (dishDtoList!=null){
           return R.success(dishDtoList);
        }

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        List<Dish> list = dishService.list(new LambdaQueryWrapper<Dish>()
                .eq((dish.getCategoryId()) != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)//起售状态
                .like(!StringUtil.isNullOrEmpty(dish.getName()), Dish::getName, dish.getName()));

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
